package cb

import (
	"net/http"
  "fmt"
	"github.com/labstack/echo"
  ewa "gitee.com/jinquan711/ewa"
  "database/sql"
  _ "github.com/go-sql-driver/mysql"
)

type userTB struct {
  Id      int
  Devicetype  sql.NullString
}
type DbWorker struct {
  Db       *sql.DB
  UserInfo userTB
}

func (dbw *DbWorker) QueryDataPre() {
  dbw.UserInfo = userTB{}
}
func (dbw *DbWorker) queryData(Uacode string) string {
  stmt, _ := dbw.Db.Prepare(`SELECT id,device_type From UA_DEVICE where ua_code = ?`)
  defer stmt.Close()

  dbw.QueryDataPre()
  
  //fmt.Println(dbw.Db.Stats())
  //sql := fmt.Sprintf( "SELECT id,device_type From UA_DEVICE where ua_code = '%s';", Uacode )
  //fmt.Println(sql)
  //rows, err := dbw.Db.Query(sql)
  rows, err := stmt.Query(Uacode)
  defer rows.Close()
  if err != nil {
    l:=fmt.Sprintf("---MySQL/> Select data error: %v\n", err); ewa.Log(l)
    return "null"
  }
  for rows.Next() {
    rows.Scan(&dbw.UserInfo.Id, &dbw.UserInfo.Devicetype)
    if err != nil {
      m:=fmt.Sprintf("---MySQL/> %v\n", err.Error()); ewa.Log(m)
      continue
    }
    if !dbw.UserInfo.Devicetype.Valid {
      dbw.UserInfo.Devicetype.String = "null"
    } else {
      //fmt.Println("---MySQL/> get data, id: ", dbw.UserInfo.Id, " device type: ", dbw.UserInfo.Devicetype.String )
      return dbw.UserInfo.Devicetype.String
    }
  }

  err = rows.Err()
  if err != nil {
    n:=fmt.Sprintf("---MySQL/> %v\n", err.Error()); ewa.Log(n)
  }
  return "null"
}

/* Non-Restrict Route POST, 
   不需要cookies, 
   不需要token验证  */
func Cb_get_device_type(c echo.Context) error {
  ua_code := c.FormValue("ua_code")
  if ewa.Logoption.Echorequest == "true" {
    l:=fmt.Sprintf("----Echo/> client post parameter: %s", ua_code); ewa.Log(l)
  }
  utype, uri := ewa.HttpReqPathSuffix(c.Path())
  if utype == ewa.URITYPE_RES {

  }else if utype == ewa.URITYPE_API {
      var dbw DbWorker
      dbw.Db = ewa.CreateMysqlConn(ewa.MysqlConnArgs_)
      device_type:=dbw.queryData(ua_code)
      if ewa.Logoption.Mysqlquery == "true" {
        r:=fmt.Sprintf("---MySQL/> DB query result: %s", device_type); ewa.Log(r)
      }
      ewa.CloseMysqlConn(dbw.Db)
      if ewa.Logoption.Apichain == "true" {
        m:=fmt.Sprintf("Apichain/> %s \"%s\" %s@(%s:%d)/%s \"%s\"", uri, ua_code, 
            ewa.MysqlConnArgs_.Username,
            ewa.MysqlConnArgs_.Server,
            ewa.MysqlConnArgs_.Port,
            ewa.MysqlConnArgs_.Database, 
            device_type); ewa.Log(m)
      }
      return c.String(http.StatusOK, device_type)
  }
  return nil
}
